package designPattern;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 命令模式
 */
public class CommandPattern {
    public static void main(String[] args) {
        Stock stock = new Stock();
        Order buyOrder = new BuyStock(stock);
        Order sellOrder = new SellStock(stock);

        Broker broker = new Broker();
        broker.takeOrder(buyOrder);
        broker.takeOrder(sellOrder);
        broker.placeOrder();
    }
}

//接口
interface Order {
    void execute();
}

//控制中心
class Broker {
    List<Order> orders = new ArrayList<>();

    public void takeOrder(Order order) {
        this.orders.add(order);
    }

    public void placeOrder() {
        for (Order order : this.orders) {
            order.execute();
        }
    }
}

//实际实现
class Stock {
    private String name = "Mio";
    private int quantity = 10;

    public void buy() {
        System.out.println("Stock [ Name: "+name+", Quantity: " + quantity +" ] bought");
    }

    public void sell() {
        System.out.println("Stock [ Name: "+name+", Quantity: " + quantity +" ] sold");
    }
}

//中间调用实现
class BuyStock implements Order {

    private Stock stock;

    public BuyStock(Stock stock) {
        this.stock = stock;
    }

    @Override
    public void execute() {
        stock.buy();
    }
}

class SellStock implements Order {

    private Stock stock;

    public SellStock(Stock stock) {
        this.stock = stock;
    }

    @Override
    public void execute() {
        stock.sell();
    }
}